﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Common.Library;
using OnlineVideos.Entities;
using OnlineVideos.Data;
using System.IO.IsolatedStorage;
using OnlineVideos.Common;
using OnlineVideos;

namespace OnlineVideos
{
    public partial class DownloadbleShowList : UserControl
    {
        #region GlobalDeclaration
        List<DownloadStatus> downloadStatus = new List<DownloadStatus>();
        #endregion

        #region PageLoad
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (AppSettings.AddNewShowIconVisibility)
            {
                AddList();
            }
        }
        #endregion

        #region Constructor
        public DownloadbleShowList()
        {
            InitializeComponent();
           
        }
        #endregion

        #region Events
        void wb_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {

                    string filepath = "";
                    string FileName = "";
                    string path = "";
                    string FolderStatus = "";

                    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                    bool Check = CheckSpace(e.Result.Length);
                    if (Check == true)
                    {
                        long RequiredSize = e.Result.Length;
                        byte[] SaveFile = new byte[RequiredSize];
                        var xquery = from p in downloadStatus where p.Id == Convert.ToInt32(e.UserState) select p;
                        foreach (var itm in xquery)
                        {
                            FileName = itm.RequestUri.ToString().Substring(itm.RequestUri.ToString().LastIndexOf('/') + 1);
                            path = itm.RequestUri.ToString();
                            FolderStatus = itm.FolderStatus;
                        }

                        string ext = System.IO.Path.GetExtension(FileName);
                        if (FolderStatus != "Folder")
                        {
                            if (ext == ".doc")
                            {
                                if (!isoStore.DirectoryExists(ResourceHelper.DirectoryName + "/Documents"))
                                    isoStore.CreateDirectory(ResourceHelper.DirectoryName + "/Documents");
                                filepath = ResourceHelper.DirectoryName + "/Documents" + FileName;
                            }
                            else if (ext == ".3gp" || ext == ".3g2" || ext == ".mp4" || ext == ".m4v" || ext == ".wmv")
                            {
                                if (!isoStore.DirectoryExists(ResourceHelper.DirectoryName + "/Videos"))
                                    isoStore.CreateDirectory(ResourceHelper.DirectoryName + "/Videos");
                                filepath = "/" + ResourceHelper.DirectoryName + "/Videos/" + FileName;
                            }
                            else if (ext == ".mp3" || ext == ".wav" || ext == ".aac" || ext == ".amr" || ext == ".wma")
                            {
                                if (!isoStore.DirectoryExists(ResourceHelper.DirectoryName + "/Songs"))
                                    isoStore.CreateDirectory(ResourceHelper.DirectoryName + "/Songs");

                                filepath = "/" + ResourceHelper.DirectoryName + "/Songs/" + FileName;
                            }
                            else
                            {
                                if (!isoStore.DirectoryExists(ResourceHelper.DirectoryName + "/Images"))
                                    isoStore.CreateDirectory(ResourceHelper.DirectoryName + "/Images");
                                filepath = "/" + ResourceHelper.DirectoryName + "/Images/" + FileName;
                            }

                            IsolatedStorageFileStream isoFile = new IsolatedStorageFileStream(filepath, System.IO.FileMode.Create, isoStore);
                            e.Result.Read(SaveFile, 0, SaveFile.Length);
                            isoFile.Write(SaveFile, 0, SaveFile.Length);
                            DownloadManager.DeleteDownloadUrls(path);
                            DownloadManager.DownloadingStatus(filepath);
                        }
                        else
                        {
                            if (!isoStore.DirectoryExists(ResourceHelper.DirectoryName + "/" + AppSettings.DownloadFolderName))
                                isoStore.CreateDirectory(ResourceHelper.DirectoryName + "/" + AppSettings.DownloadFolderName);
                            filepath = ResourceHelper.DirectoryName + "/" + AppSettings.DownloadFolderName + "/" + FileName;
                            IsolatedStorageFileStream isoFile = new IsolatedStorageFileStream(filepath, System.IO.FileMode.Create, isoStore);
                            e.Result.Read(SaveFile, 0, SaveFile.Length);
                            isoFile.Write(SaveFile, 0, SaveFile.Length);
                            DownloadManager.DeleteDownloadUrls(path);
                            DownloadManager.DownloadingFolderStatus(filepath);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No Space Available ");
                    }
                }
            }
            catch (Exception ex)
            {
                
                    Exceptions.SaveOrSendExceptions("Exception in wb_OpenReadCompleted Method In DownloadbleShowList.cs file.", ex);
            }
        }
        void wb_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                if (e.BytesReceived < e.TotalBytesToReceive)
                {
                    foreach (DownloadStatus d in downloadStatus)
                    {
                        if (d.Id.ToString() == e.UserState.ToString())
                        {
                            d.ChapterProgressPosition = e.ProgressPercentage;
                        }
                    }
                }
                else
                {
                    tblkNoDownloads.Visibility = Visibility.Visible;
                    lbxdownloading.Visibility = Visibility.Collapsed;
                    //DataBindTopRatedAndRecentShows();
                }

            }
            catch (Exception ex)
            {
                string excepmess = "Exception in wb_DownloadProgressChanged Method In Videos file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in wb_DownloadProgressChanged Method In DownloadbleShowList.cs file.", ex);
            }
        }
        #endregion

        #region "Common Methods"
        public void AddList()
        {
            try
            {
                int i = 0;
                List<DownloadInfo> objVideoList = new List<DownloadInfo>();

                objVideoList = DownloadManager.LoadDownloadUrls();

                int countlist = objVideoList.Count();
                if (countlist > 0)
                {
                    var xquery = (from q in objVideoList select q);

                    foreach (DownloadInfo download in objVideoList)
                    {
                        i++;
                        string link = "";
                        link = download.LinkUrl;
                        string name = "";
                        name = download.LinkUrl.ToString().Substring(download.LinkUrl.ToString().LastIndexOf('/') + 1);
                        var ln = link;

                        WebClient wb = new WebClient();
                        wb.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wb_DownloadProgressChanged);
                        wb.OpenReadCompleted += new OpenReadCompletedEventHandler(wb_OpenReadCompleted);
                        wb.OpenReadAsync(new Uri(link.ToString(), UriKind.Absolute), i.ToString());

                        LoadList(name, link, i);
                        lbxdownloading.ItemsSource = downloadStatus;
                    }
                }
                else
                {
                    tblkNoDownloads.Visibility = Visibility.Visible;
                    lbxdownloading.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in AddList Method In DownloadbleShowList.cs file.", ex);
            }
        }
        public void LoadList(string Title, string link, int i)
        {
            try
            {
                List<DownloadInfo> DownloadedItems = new List<DownloadInfo>();
                string folderStatus = string.Empty;

                DownloadedItems = DownloadManager.LoadDownloadUrls();
                foreach (var download in DownloadedItems)
                {
                    folderStatus = download.DownloadStatus;
                }

                if (DownloadedItems.Count() != 0)
                {
                    DownloadStatus d = new DownloadStatus();
                    d.Id = i;
                    d.Title = Title;
                    d.FolderStatus = folderStatus;
                    d.ChapterProgressPosition = 0;
                    d.RequestUri = new Uri(link);
                    downloadStatus.Add(d);
                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in LoadList Method In DownloadbleShowList.cs file.", ex);
            }
        }
        protected bool CheckSpace(long size)
        {
            bool SpaceAvailable = false;
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            long AvailableSpace = isoStore.AvailableFreeSpace;
            if (size > AvailableSpace)
            {
                if (!isoStore.IncreaseQuotaTo(isoStore.Quota + size))
                {
                    SpaceAvailable = false;
                }
                else
                {
                    SpaceAvailable = true;
                }
            }
            else
            {
                SpaceAvailable = true;
            }

            return SpaceAvailable;
        }
        #endregion



    }
}
